package com.you.concurrent.blockingqueue;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

public class ArrayBlockingQueueDemo {

    static ArrayBlockingQueue<Integer> arrayBlockingQueue = new ArrayBlockingQueue(5);


    public static void main(String[] args) {
        //生产者
        for (int i = 0; i < 10; i++) {
            final int index = i + 1;
            new Thread(() -> {
                int count = 0;
                do {
                    try {
                        Thread.sleep(10L);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    try {
                        //arrayBlockingQueue.add(count * index);
                        //arrayBlockingQueue.offer(count * index);
                        arrayBlockingQueue.put(count * index);
                        System.out.println(Thread.currentThread().getName() + " put num = " + count * index);
                        count++;
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                } while (true);
            }).start();
        }
        //消费者
        for (int i = 0; i < 3; i++) {
            new Thread(() -> {
                while (true) {
                    try {
                        Thread.sleep(100L);
                        Integer num = arrayBlockingQueue.take();
                        System.out.println("------------" + Thread.currentThread().getName() + " get num = " + num);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
    }
}
